package logic.files;

import database.IDBObject;
import database.Record;
import logic.baselogic.Database;

import java.io.*;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: grigory.rozhkov
 * Date: 12.09.12
 * Time: 23:25
 * To change this template use File | Settings | File Templates.
 */
public class SimpleFileDatabaseLoader implements IDatabaseLoader {
    public Database loadBase() {
        Database newDatabase = new Database();

        FileInputStream fileInputStream = null;

        try {
            fileInputStream = new FileInputStream("src/database/save/db");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        if (fileInputStream != null) {
            ArrayList<IDBObject> newBaseList = new ArrayList<IDBObject>();

            DataInputStream inputStream = new DataInputStream(fileInputStream);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String id;
            try {
                while ((id = bufferedReader.readLine()) != null) {
                    Record tempRecord = new Record();
                    tempRecord.create(id, bufferedReader.readLine());
                    newBaseList.add(tempRecord);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            newDatabase.setBaseList(newBaseList);
        }
        return newDatabase;
    }
}
